/*
 * @Author: Smile
 * @Date: 2021-02-01 13:43:55
 * @LastEditTime: 2021-02-01 13:58:39
 * @LastEditors: Smile
 * @Description: remarks
 */
// 请求地址的基本路径
import { BASE_API, BASE_LOGIN_API } from "./config";
import { Logs } from "./log";
const logs = new Logs();

export const request = (url, method = 'GET', data = {}, header = {
  'Content-Type': 'application/x-www-form-urlencoded',
}) => { 
  // 显示加载数据的提示
  wx.showLoading({
    title: '加载中',
    mask: true
  })

  let userLoginState = wx.getStorageSync('userLoginState') || ''
  let router = ''
  if (url === '/miniProgramController/onLogin') {
    router = BASE_LOGIN_API+url
  }else{
    router = BASE_API+url +'?userLoginState='+userLoginState
  }
  // let url = BASE_API + path + '?userLoginState='+userLoginState
  logs.info('============ 请求接口 ============')
  logs.info(router)
  logs.info('============ 请求参数 ============')
  logs.info(data)
  return new Promise(function (resolve, reject) {
    // 这个位置进行异步操作
    wx.request({
      url:router,
      method,
      data,
      header,
      success: function (res) {
        wx.hideLoading()
        console.log('%c⧭', 'color: #1d3f73', res.data, '成功--请求.js');
        logs.info('============ 请求成功后的数据 ============')
        logs.info(res.data)

        if (!res.data.success && res.data.errorMessage) {
          wx.showToast({
            title: res.data.errorMessage,
            icon: 'none',
            mask: true
          })
        }

        if (res.data.error) {
          wx.showToast({
            title: '请求失败!',
            icon: 'none',
            mask: true
          })
        }
        resolve(res.data)
      },
      fail: function (err) {
        wx.hideLoading()
        console.log('%c⧭', 'color: #1d3f73', err, '失败--请求.js');
        logs.info('============ 请求失败后的数据： ============')
        logs.info(err)
        wx.showToast({
          title: '请求失败！',
          icon: 'none',
          mask: true
        })
        reject(err)
      },
    })
  }) 
}
